package com.tongguan.paypos.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;

import com.basewin.aidl.OnPrinterListener;
import com.basewin.define.FontsType;
import com.basewin.services.PrinterBinder;
import com.basewin.services.ServiceManager;
import com.tongguan.paypos.R;
import com.tongguan.paypos.activity.menu.TransSettleActivity;
import com.tongguan.paypos.adapter.ManageAdapter;
import com.tongguan.paypos.base.BaseFragment;
import com.tongguan.paypos.common.AppConstants;
import com.tongguan.paypos.common.CountTotal;
import com.tongguan.paypos.common.RequestCallback;
import com.tongguan.paypos.common.UrlConstants;
import com.tongguan.paypos.common.User;
import com.tongguan.paypos.entity.Manage;
import com.tongguan.paypos.entity.MoneyCount;
import com.tongguan.paypos.entity.PrintLastInfo;
import com.tongguan.paypos.entity.PrintRepeat;
import com.tongguan.paypos.entity.SettleResult;
import com.tongguan.paypos.entity.SettleTotal;
import com.tongguan.paypos.entity.Total;
import com.tongguan.paypos.entity.TransUnionInfo;
import com.tongguan.paypos.utils.AppUtils;
import com.tongguan.paypos.utils.Arith;
import com.tongguan.paypos.utils.FileUtils;
import com.tongguan.paypos.utils.L;
import com.tongguan.paypos.utils.PrintUtils;
import com.tongguan.paypos.utils.ToastUtils;
import com.tongguan.paypos.utils.Utils;
import com.tongguan.paypos.view.CustomAlertDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by JoyLive on 2016/12/16
 */

public class PrintModuleFragment extends BaseFragment {
    private static final int PRINT_LAST = 10060;
    private String pathName = AppConstants.CACHE_DIR + TransSettleActivity.CACHE_NAME;
    @BindView(R.id.gv_print_module)
    GridView mGvPrintModule;
    private List<Total> mTotals ;
    private String lastTime, thisTime;
    private PrintRepeat mPrintRepeat;
    private boolean isCoupon = false;//是否优惠
    private double money;//实付金额
    private double coupon_money;//优惠金额
    private double amount;//总金额
    private MoneyCount mMoneyCount;
    private int index = 0;
    private ManageAdapter adapter;
    private PrinterListener mPrinterListener = new PrinterListener();
    private PrinterSettleListener mSettleListener = new PrinterSettleListener();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_print_module, container, false);
        ButterKnife.bind(this, rootView);
        setTitle("打印");
        ArrayList<Manage> arrayList = new ArrayList<>();
        arrayList.add(new Manage(R.drawable.ic_print_last, "重打最后一笔", "0"));
        arrayList.add(new Manage(R.drawable.ic_print_at_will, "重打任意一笔", "1"));
        arrayList.add(new Manage(R.drawable.ic_print_total, "重打结算总计", "2"));
        adapter = new ManageAdapter(frmCtx, arrayList);
        mGvPrintModule.setAdapter(adapter);
        initEvent();
        return rootView;
    }

    private void initEvent() {
        mGvPrintModule.setOnItemClickListener((parent, view, position, id) -> {
            Manage item = adapter.getItem(position);
            switch (item.getFragmentName()) {
                case "0":
                    new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.common_tip_title)
                            .setMessage("重打印最后一笔")
                            .setPositiveButton(R.string.common_sure, (dialog, which) -> printLast())
                            .setNegativeButton(R.string.common_cancel, null).show();
                    break;
                case "1":
                    getFragmentManager().beginTransaction().replace(R.id.container, new PrintRandomFragment()).addToBackStack(null).commit();
                    break;
                case "2":
                    new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.common_tip_title)
                            .setMessage("重打结算总计单")
                            .setPositiveButton(R.string.common_sure, (dialog, which) -> printTotal())
                            .setNegativeButton(R.string.common_cancel, null).show();
                    break;
            }
        });
    }

    //打印最后一笔
    private void printLast() {
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_POS_ID, User.getInstance().getPosId());
        RequestCallback.post(frmCtx, UrlConstants.PRINT_ORDER_LAST, params, mDialog, new AbstractRequestCallback() {
            @Override
            public void onResponse(String response, int id) {
                PrintLastInfo printResponseInfo = PrintLastInfo.objectFromData(response);
                if (printResponseInfo.getStatus() != 100) {
                    ToastUtils.showCustom(frmCtx, printResponseInfo.getMessage());
                    return;
                }
                mPrintRepeat = printResponseInfo.getPrintRepeat();
                if (mPrintRepeat == null) {
                    ToastUtils.showCustom(frmCtx, "data is null ...");
                    return;
                }
                //其他支付方式跳转
                String type = mPrintRepeat.getChannelId();
                if ("YL".equals(type)) { //银联刷卡
                    AppUtils.runComponent(frmCtx, AppConstants.UNION_PAY_APP_PACKAGE, AppConstants.PRINT_LAST_DIR, null, PRINT_LAST);
                    return;
                } else if ("DK".equals(type)) {
                    ToastUtils.showCustom(frmCtx, "此版本暂不开放！");
                    return;
                } else if ("XL".equals(type)) {
                    ToastUtils.showCustom(frmCtx, "不支持打印此笔外卡交易！");
                    return;
                }
                money = mPrintRepeat.getPayMoney();
                coupon_money = mPrintRepeat.getCouponMoney();
                if (coupon_money > 0) {
                    isCoupon = true;
                    amount = Arith.sub(money, coupon_money);
                } else {
                    amount = money;
                }
                mMoneyCount = new MoneyCount(money, coupon_money, amount);
                if (mDialog != null && !mDialog.isShowing()) {
                    mDialog.setLoadingMessage("打印中...");
                    mDialog.show();
                }
                mHandler.sendEmptyMessageDelayed(0, 500);
            }
        });
    }

    //打印结算总计
    public void printTotal() {
        boolean fileExist = FileUtils.isFileExist(pathName);
        if (!fileExist) {
            ToastUtils.showCustom(frmCtx, "暂无批结算数据！");
            L.d("文件不存在");
            return;
        }
        String jsonData = FileUtils.readFile(pathName);
        if (TextUtils.isEmpty(jsonData)) {
            ToastUtils.showCustom(frmCtx, "暂无批结算数据！");
            return;
        }
        SettleResult settleResult = SettleResult.objectFromData(jsonData);
        lastTime = settleResult.getLastTime();
        thisTime = settleResult.getThisTime();
        List<SettleTotal> totalList = settleResult.getTotalList();
        if (totalList.size() > 0) {
            mTotals = CountTotal.getCountTotal(totalList);
        } else {
            ToastUtils.showCustom(frmCtx, "暂无结算数据!");
            return;
        }
        if (!mDialog.isShowing()) {
            mDialog.setLoadingMessage("打印中...");
            mDialog.show();
        }
        mHandler.sendEmptyMessageDelayed(3, 500);
    }

    /*重打印*/
    private void printerRepeat(int printIndex) {
        new Thread(() -> {
            try {
                PrinterBinder printer = ServiceManager.getInstence().getPrinter();
                printer.setPrintGray(1500);
                printer.setPrintFont(FontsType.simsun);
                printer.cleanCache();
                String data = PrintUtils.printRepeatOrder(mPrintRepeat, printIndex, isCoupon, mMoneyCount);
                mPrinterListener.isRepeat = false;
                printer.print(data,null,mPrinterListener);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 打印结算
     */
    private void printerTotal() {
        new Thread(() -> {
            try {
                PrinterBinder printer = ServiceManager.getInstence().getPrinter();
                printer.setPrintGray(1500);
                printer.setPrintFont(FontsType.simsun);
                printer.cleanCache();
                String data = PrintUtils.printSettleTotal(mTotals, lastTime, thisTime,true);
                mSettleListener.isRepeat = false;
                printer.print(data,null,mSettleListener);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (!frmCtx.isFinishing()) {
                switch (msg.what) {
                    case 0: //延时打印
                        printerRepeat(index);
                        break;
                    case 1:
                        if (mDialog != null && mDialog.isShowing()) {
                            mDialog.dismiss();
                        }
                        if (index == 0) {
                            new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.common_tip_title)
                                    .setMessage("请撕下票据")
                                    .setPositiveButton("打印下一联", (dialog, which) -> {
                                        if (!mDialog.isShowing()) {
                                            mDialog.show();
                                        }
                                        index++;
                                        mHandler.sendEmptyMessageDelayed(0, 500);
                                    }).setNegativeButton("退出打印", (dialog, which) -> {
                            }).setTimer(true).show();
                        }
                        //其它不打印
                        if (index == 1) {
                            index = 0;//打印页复原
                        }
                        break;
                    case 2: //打印异常重打印
                        if (mDialog != null && mDialog.isShowing()) {
                            mDialog.dismiss();
                        }
                        String message = (String) msg.obj;
                        new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.common_tip_title)
                                .setMessage("异常 " + message)
                                .setPositiveButton("重新打印", (dialog, which) -> {
                                    if (mDialog != null && !mDialog.isShowing()) {
                                        mDialog.show();
                                    }
                                    mHandler.sendEmptyMessage(0);
                                }).setNegativeButton("退出", null).show();
                        break;

                    case 3:
                        printerTotal();
                        break;
                    case 4:
                        if (mDialog != null && mDialog.isShowing()) {
                            mDialog.dismiss();
                        }
                        String message2 = (String) msg.obj;
                        new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.common_tip_title)
                                .setMessage("异常 " + message2)
                                .setPositiveButton("重新打印", (dialog, which) -> {
                                    if (mDialog != null && !mDialog.isShowing()) {
                                        mDialog.show();
                                    }
                                    mHandler.sendEmptyMessage(3);
                                }).setNegativeButton("退出", null).show();
                        break;
                    case 5:
                        if (mDialog != null && mDialog.isShowing()) {
                            mDialog.dismiss();
                        }
                        break;

                }
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        L.d("requestCode = " + requestCode + " resultCode = " + resultCode);
            //银联
            if (requestCode == PRINT_LAST) {
                if (resultCode == Activity.RESULT_OK) {
                    String result = data.getStringExtra("result");
                    String message = Utils.assembleTransUnionInfo(result, true);
                    L.d(message);
                    frmCtx.finish();
                } else {
                    ToastUtils.showCustom(frmCtx, "失败");
                }
        }
    }

    private class PrinterListener implements OnPrinterListener{
        boolean isRepeat = false;
        @Override
        public void onStart() {
            // TODO 打印开始
            L.d(" 打印开始");
        }

        @Override
        public void onFinish() {
            // TODO 打印结束
            L.d(" 打印结束");
            mHandler.sendEmptyMessage(1);
        }

        @Override
        public void onError(int errorCode, String detail) {
            // TODO 打印出错
            L.d(" 打印出错");
            if (!isRepeat) {
                isRepeat = true;
                if (errorCode == PrinterBinder.PRINTER_ERROR_NO_PAPER) {
                    mHandler.sendMessage(mHandler.obtainMessage(2, detail));
                } else {
                    ToastUtils.showCustom(frmCtx, detail + "--" + errorCode);
                }
            }
        }
    }


    private class PrinterSettleListener implements OnPrinterListener{
        boolean isRepeat = false;
        @Override
        public void onStart() {
            // TODO 打印开始
            L.d(" 打印开始");
        }

        @Override
        public void onFinish() {
            // TODO 打印结束
            L.d(" 打印结束");
            mHandler.sendEmptyMessage(5);
        }

        @Override
        public void onError(int errorCode, String detail) {
            // TODO 打印出错
            L.d(" 打印出错");
            if (!isRepeat) {
                isRepeat = true;
                if (errorCode == PrinterBinder.PRINTER_ERROR_NO_PAPER) {
                    mHandler.sendMessage(mHandler.obtainMessage(4, detail));
                } else {
                    ToastUtils.showCustom(frmCtx, detail + "--" + errorCode);
                }
            }
        }
    }

}
